package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.geoaimavlink_android.R
import kotlinx.android.synthetic.main.frag_compass_calibration.btn_start_calibration
import kotlinx.android.synthetic.main.frag_compass_calibration.btn_stop_calibration
import kotlinx.android.synthetic.main.frag_compass_calibration.tv_compass_calibration_info

class CompassCalibrationFragment : BaseFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_compass_calibration, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initSDK()
    }

    private fun initSDK() {
        msdkInfoVm.msdkInfo.observe(viewLifecycleOwner) {
            if (it.isAircraftConnected) {
                getProduct()?.flyControllerManager?.setCalibrationCompassListener {stateInfo ->
                    tv_compass_calibration_info?.text = format(gson.toJson(stateInfo))
                }
            } else {
                getProduct()?.flyControllerManager?.setCalibrationCompassListener(null)
            }
        }
    }

    private fun initView() {
        btn_start_calibration.setOnClickListener {
            getProduct()?.flyControllerManager?.let { flyControllerManager ->
                flyControllerManager.startCalibrationCompass {
                    showToast(it?.description?:"success")
                }
            }
        }
        btn_stop_calibration.setOnClickListener {
            getProduct()?.flyControllerManager?.stopCalibrationCompass {
                showToast(it?.description?:"success")
            }
        }
    }

    override fun onDestroyView() {
        getProduct()?.flyControllerManager?.setCalibrationCompassListener(null)
        super.onDestroyView()
    }

}